import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { insertCartAPI, finNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()

    const token = userStore.userInfo.token

    // 定义state cartList
    const cartList = ref([])
    //定义action addCart
    const addCart = async (goods) => {
      if (token) {
        const { skuId, count } = goods
        // 登陆后加入购物车
        await insertCartAPI({ skuId, count })
        updateNewList()
      } else {
        //添加购物车操作
        //已添加过count++
        //没有添加过，push
        const item = cartList.value.find((item) => item.skuId === goods.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    //删除购物车
    // 删除购物车
    const delCart = async (skuId) => {
      if (token) {
        // 调用接口实现接口购物车中的删除功能
        await delCartAPI([skuId])
        updateNewList()
      } else {
        // 思路：
        // 1. 找到要删除项的下标值 - splice
        // 2. 使用数组的过滤方法 - filter
        const idx = cartList.value.findIndex((item) => skuId === item.skuId)
        cartList.value.splice(idx, 1)
      }
    }

    const updateNewList = async () => {
      const res = await finNewCartListAPI()
      cartList.value = res.result
    }

    // 单选回调
    const singleCheck = (selected, skuId) => {
      console.log(selected, skuId)
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    //全选功能
    const allCheck = (selected) => {
      //将cartList中的selected全部设置为传进来的全选框状态
      cartList.value.forEach((item) => (item.selected = selected))
    }

    //计算属性
    //1、计算总数
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    //2、计算总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    //是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    //计算已选择数量的总价
    const selectedPrice = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    )
    //已选择商品合计数量
    const selectedCount = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0)
    )

    return {
      cartList,
      allCount,
      allPrice,
      isAll,
      selectedPrice,
      selectedCount,
      addCart,
      delCart,
      singleCheck,
      allCheck
    }
  },
  {
    persist: true
  }
)
